import { reqCartList, reqDeleteCartItem, reqCheckCartItem } from "@/api";
const actions = {
    //获取购物车数据
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },
    //删除购物车数据
    async deleteCartItemById({ commit }, skuId) {
        let result = await reqDeleteCartItem(skuId);
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("删除购物车数据失败！"))
        }
    },
    //修改产品勾选状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqCheckCartItem(skuId, isChecked);
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("修改产品勾选状态失败！"))
        }
    },
    //删除选中的产品
    deleteAllCheckedCart({ dispatch, getters }) {
        let promiseAll = [];
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch("deleteCartItemById", item.skuId) : ''
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    },
    //修改全部产品的勾选状态
    updateAllCheckedById({ dispatch, state }, isChecked) {
        let promiseAll = [];
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch("updateCheckedById", { skuId: item.skuId, isChecked })
            promiseAll.push(promise);
        });
        return Promise.all(promiseAll)
    }
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
}
const state = {
    cartList: []
}
const getters = {
    cartList(state) {
        return state.cartList[0] || []
    }
}
export default {
    namespaced: true,
    actions,
    mutations,
    state,
    getters
}